package two_xia.ex2.three01;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.lang.reflect.Constructor;

public class PersonUtil {
    public static Person getPersonType(String s) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            //这个路径是你的xml文件
            Document doc = db.parse("src/two_xia/ex2/three01/PersonData.xml");

            NodeList nodeList = doc.getElementsByTagName("class");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                String type = element.getAttribute("type");
                String className = element.getAttribute("name");
                if (s.equals(type)) {
                    Class<?> cls = Class.forName(className);
                    Constructor<?> constructor = cls.getConstructor();
                    Object obj = constructor.newInstance();
                    /*下面这个是调用obj的方法的，我们这里不用，直接返回这个对象*/
                    //Method method = cls.getMethod("create");
                    //method.invoke(obj);
                    return (Person) obj;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

